package com.xxx.common.shardingsphere.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.sharding.api.sharding.hint.HintShardingAlgorithm;
import org.apache.shardingsphere.sharding.api.sharding.hint.HintShardingValue;
import org.springframework.util.CollectionUtils;

import java.util.Collection;


@Slf4j
public class DataBaseShardingAlgorithm implements HintShardingAlgorithm<String> {

    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, HintShardingValue<String> hintShardingValue) {

        Collection<String> dataSourceName = hintShardingValue.getValues();

        if (CollectionUtils.isEmpty(dataSourceName)) {
            throw new IllegalStateException("MDC 获取租户失败");
        }

        // 检查数据源是否可用
        if (availableTargetNames.containsAll(dataSourceName)) {
            return dataSourceName;
        }

        throw new IllegalArgumentException("未找到对应租户的数据源: " + dataSourceName);
    }

}
